<!--
 * @Descripttion: 财务管理
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2021-03-15 14:27:25
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @LastEditTime: 2023-09-07 14:07:24
-->
<template>
  <div class="lb-finance">
    <top-nav />
    <div class="page-main">
      <el-row class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm.list"
          ref="listForm"
        >
          <el-form-item label="输入查询" prop="coach_name">
            <el-input
              v-model="searchForm.list.coach_name"
              :placeholder="'请输入' + $t('action.attendantName') + '名称'"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'list')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('list')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-table
        v-loading="loading.list"
        :data="tableData.list"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column
          prop="work_img"
          :label="`${$t('action.attendantName')}头像`"
          min-width="120"
          fixed
        >
          <template slot-scope="scope">
            <lb-image :src="scope.row.work_img" />
          </template>
        </el-table-column>
        <el-table-column
          prop="coach_name"
          :label="`${$t('action.attendantName')}姓名`"
          min-width="120"
          fixed
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          min-width="120"
          fixed
        ></el-table-column>
        <el-table-column prop="create_time" label="申请时间" min-width="120">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="" min-width="140">
          <template slot="header" slot-scope="scope">
            <div style="margin-top: 7px">
              认证状态
              <lb-tool-tips padding="11">实名认证状态</lb-tool-tips>
            </div>
          </template>
          <template slot-scope="scope">
            <el-tag :type="authStatusText[scope.row.auth_status].type">{{
              authStatusText[scope.row.auth_status].text
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="120">
          <template slot-scope="scope">
            <el-tag :type="statusText[scope.row.status].type">
              {{ statusText[scope.row.status].text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="staff_text" label="收入（元）" min-width="120">
          <template slot-scope="scope">
            <div class="flex-column">
              <div class="c-success">+¥{{ scope.row.order_price }}</div>
              <div>{{ scope.row.order_count }}笔</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total_price" label="提现（元）" min-width="120">
          <template slot-scope="scope">
            <div class="flex-column">
              <div class="c-warning">-¥{{ scope.row.total_price }}</div>
              <div>{{ scope.row.total_count }}笔</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="total_price"
          label="实际到账（元）"
          min-width="120"
        >
          <template slot-scope="scope">
            <div class="flex-column">
              <div class="c-success">+¥{{ scope.row.wallet_price }}</div>
              <div>{{ scope.row.wallet_count }}笔</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="service_price"
          label="服务费收入"
          min-width="120"
        >
          <template slot-scope="scope">
            <div class="c-warning">¥{{ scope.row.service_price }}</div>
            <div
              @click="toShowDialog('balance', scope.row)"
              class="c-warning cursor-pointer"
              v-show="pagePermission.includes('changeBalance')"
            >
              <i class="el-icon-edit"></i>
              {{ $t('action.changeBalance') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="car_price" label="车费收入" min-width="120">
          <template slot-scope="scope">
            <div class="c-warning">¥{{ scope.row.car_price }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="service_car_price"
          label="当前总余额"
          min-width="140"
        >
          <template slot="header" slot-scope="scope">
            <div style="margin-top: 7px">
              当前总余额
              <lb-tool-tips padding="11">包含车费收入</lb-tool-tips>
            </div>
          </template>
          <template slot-scope="scope">
            <div class="c-link">¥{{ scope.row.service_car_price }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="success"
                @click="toShowDialog('record', scope.row)"
                v-hasPermi="`${$route.name}-balanceRecord`"
                >{{ $t('action.balanceRecord') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="searchForm.list.page"
        :pageSize="searchForm.list.limit"
        :total="total.list"
        @handleSizeChange="handleSizeChange($event, 'list')"
        @handleCurrentChange="handleCurrentChange($event, 'list')"
      >
      </lb-page>

      <el-dialog
        :title="$t('action.changeBalance')"
        :visible.sync="showDialog.balance"
        width="600px"
        center
      >
        <el-form
          :model="balanceForm"
          ref="balanceForm"
          :rules="balanceFormRules"
          label-width="120px"
          class="dialog-form"
        >
          <div class="flex-center" style="margin: 0 0 10px 48px">
            <lb-image
              :src="balanceForm.avatarUrl"
              :isLook="true"
              style="width: 60px; height: 60px"
              v-if="balanceForm.avatarUrl"
            />
            <div class="flex-1 ml-md f-caption c-caption">
              <div class="f-paragraph c-title text-bold">
                {{ balanceForm.nickName }}
              </div>
              <div class="mt-sm" v-if="balanceForm.phone">
                {{ balanceForm.phone }}
              </div>
              <div class="mt-sm">
                原服务费收入：<span class="c-warning"
                  >¥{{ balanceForm.price }}</span
                >
              </div>
            </div>
          </div>
          <el-form-item label="选择增减方式" prop="type">
            <el-radio-group v-model="balanceForm.type">
              <el-radio :label="1">增加余额</el-radio>
              <el-radio :label="0">减扣余额</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            :label="balanceForm.type === 1 ? '增加余额' : '减扣余额'"
            prop="new_price"
          >
            <el-input
              v-model="balanceForm.new_price"
              placeholder="请输入金额"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注信息" prop="text">
            <el-input
              type="textarea"
              resize="none"
              :rows="5"
              v-model="balanceForm.text"
              placeholder="请输入金额变动的原因"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.balance = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitFormInfo('balance')"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        :title="$t('action.balanceRecord')"
        :visible.sync="showDialog.record"
        width="800px"
        center
      >
        <el-table
          v-loading="loading.record"
          :data="tableData.record"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="120"></el-table-column>
          <el-table-column
            prop="create_user"
            label="操作者"
            width="120"
          ></el-table-column>
          <el-table-column prop="" label="操作记录" min-width="200">
            <template slot-scope="scope">
              <span
                :class="[
                  { 'c-link': scope.row.is_add },
                  { 'c-warning': !scope.row.is_add }
                ]"
                >{{
                  `${scope.row.is_add ? '+' : '-'} ¥${scope.row.cash}`
                }}</span
              >
              ，现余额<span class="ml-sm c-success"
                >¥{{ scope.row.after_cash }}</span
              >
              <el-popover placement="top-start" width="400" trigger="hover">
                <div class="f-caption c-title" slot>
                  <div class="c-caption pb-sm">操作原因：</div>
                  <div v-html="scope.row.text"></div>
                </div>
                <span
                  class="iconfont iconwentifankui1 c-warning"
                  slot="reference"
                ></span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="操作时间" width="120">
            <template slot-scope="scope">
              <p>{{ scope.row.create_time | handleTime(1) }}</p>
              <p>{{ scope.row.create_time | handleTime(2) }}</p>
            </template>
          </el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.record.page"
          :pageSize="searchForm.record.limit"
          :total="total.record"
          @handleSizeChange="handleSizeChange($event, 'record')"
          @handleCurrentChange="handleCurrentChange($event, 'record')"
        >
        </lb-page>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
export default {
  data () {
    return {
      statusText: {
        1: {
          type: 'info',
          text: '申请中'
        },
        2: {
          type: '',
          text: '已授权'
        },
        3: {
          type: 'danger',
          text: '取消授权'
        },
        4: {
          type: 'danger',
          text: '已驳回'
        }
      },
      authStatusText: {
        0: {
          type: 'info',
          text: '未认证'
        },
        1: {
          type: '',
          text: '认证中'
        },
        2: {
          type: 'success',
          text: '已认证'
        },
        3: {
          type: 'warning',
          text: '已驳回'
        }
      },
      pagePermission: [],
      loading: { list: false, record: false },
      searchForm: {
        list: {
          page: 1,
          limit: 10,
          coach_name: ''
        },
        record: {
          page: 1,
          limit: 10,
          coach_id: ''
        }
      },
      tableData: { list: [], record: [] },
      total: { list: 0, record: 0 },
      storeList: [],
      showDialog: { balance: false, record: false },
      balanceForm: {
        id: '',
        nickName: '',
        avatarUrl: '',
        price: '',
        new_price: '',
        text: '',
        type: 1
      },
      balanceFormRules: {
        new_price: { required: true, validator: this.$reg.isMoney, text: '金额', trigger: 'blur' },
        text: { required: true, validator: this.$reg.isNotNull, reg_type: 2, text: '备注信息', trigger: 'blur' }
      }
    }
  },
  created () {
    this.routesItem.routes.map(item => {
      if (item.path === '/finance') {
        item.children.map(aitem => {
          if (aitem.name === 'FinanceManage') {
            this.pagePermission = aitem.meta.pagePermission[0].auth
          }
        })
      }
    })
    this.getTableDataList(1, 'list')
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    handleSizeChange (val, key) {
      this.searchForm[key].limit = val
      this.handleCurrentChange(1, key)
    },
    handleCurrentChange (val, key) {
      this.searchForm[key].page = val
      this.getTableDataList('', key)
    },
    async getTableDataList (flag, key) {
      if (flag) this.searchForm[key].page = 1
      this.loading[key] = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm[key]))
      if (key === 'list') {
        let { start_time: time } = searchForm
        if (time && time.length > 0) {
          searchForm.start_time = time[0] / 1000
          searchForm.end_time = time[1] / 1000
        } else {
          searchForm.start_time = ''
          searchForm.end_time = ''
        }
      }
      let methodArr = {
        list: { methodKey: 'finance', methodModel: 'financeList' },
        record: { methodKey: 'finance', methodModel: 'updateCoachCashList' }
      }
      let { methodKey, methodModel } = methodArr[key]
      let { code, data } = await this.$api[methodKey][methodModel](searchForm)
      this.loading[key] = false
      if (code !== 200) return
      data.data.map(item => {
        if (key === 'list') {
          item.service_car_price = (item.service_price + item.car_price).toFixed(2)
        }
        if (key === 'record') {
          item.text = item.text && item.text.length > 0 ? item.text.replace(/\n/g, '<br>') : '没有填写原因哦'
        }
      })
      this.tableData[key] = data.data
      this.total[key] = data.total
    },
    async toShowDialog (key, item = {}) {
      item = JSON.parse(JSON.stringify(item))
      item.type = 1
      if (key === 'balance') {
        item.price = item.service_price
        item.nickName = item.coach_name
        item.avatarUrl = item.work_img
        item.new_price = ''
        item.text = ''
      }
      if (key === 'record') {
        this.searchForm[key].coach_id = item.id
      }
      if (['record'].includes(key)) {
        await this.getTableDataList(1, key)
      } else {
        for (let i in this[`${key}Form`]) {
          this[`${key}Form`][i] = item[i]
        }
      }
      this.showDialog[key] = !this.showDialog[key]
    },
    async submitFormInfo (key) {
      let flag = true
      let subForm = JSON.parse(JSON.stringify(this[`${key}Form`]))
      if ((key === 'pay' && subForm.type !== 1) || key !== 'pay') {
        this.$refs[`${key}Form`].validate((valid) => {
          if (!valid) flag = false
        })
      }
      if (flag) {
        let params = {}
        let { id, type, price: oprice, new_price: cash, text } = subForm
        if (key === 'balance') {
          params = { coach_id: id, is_add: type, cash, text }
          if (!type && cash * 1 > oprice * 1) {
            this.$message.error(`扣减余额不能大于原服务费收入！`)
            return
          }
        }
        let methodArr = {
          balance: { methodKey: 'finance', methodModel: 'updateCoachCash' }
        }
        let { methodKey, methodModel } = methodArr[key]
        let { code } = await this.$api[methodKey][methodModel](params)
        if (code !== 200) return
        this.$message.success(this.$t('tips.successSub'))
        this.showDialog[key] = false
        this.getTableDataList('', 'list')
      }
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-finance {
  .page-main {
    width: 100%;

    .el-select,
    .el-input-number,
    .el-input {
      width: 200px;
    }
    .el-table {
      .table-goods-info {
        width: 280px;
        height: 80px;
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        font-size: 12px;

        .goods-info-r {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-around;

          p {
            width: 210px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .price {
            color: red;
          }
        }

        .el-image {
          min-width: 70px;
          height: 70px;
          margin-right: 10px;
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}

.none {
  display: none;
}
</style>
<style media="print">
.none {
  display: block;
}
</style>
